<template>
    <!--            任务名称-->
    <div class="todo-task-title">
        <v-checkbox class="checkbox-completeTask" color="success" @click="completeTask()"
                    v-model="curIsTaskDone"></v-checkbox>
        <div class="todo-rest">
            <span v-show="!isEditTaskName" @click="()=>{this.isEditTaskName = true}">{{taskName}}</span>

            <textarea v-show="isEditTaskName" rows="1" class="title-style" placeholder="输入任务标题"
                      @blur.prevent="taskNameTextLoseFocus"
                      @keydown="(e) => keydownTaskName(e)" @keyup="(e) => keyupTaskName(e)" id="todo_content"
                      v-model="curTaskName"></textarea>
        </div>
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Prop, Model } from 'vue-property-decorator';
    import TaskService from "@service/task/task-service";

    @Component({})
    export default class AppTaskname extends Vue {

        /**
         * 应用上下文
         *
         * @type {*}
         * @memberof TaskInfoBase
         */
        @Prop() public context: any;

        /**
         * 视图参数
         *
         * @type {*}
         * @memberof TaskInfoBase
         */
        @Prop() public viewparams: any;


        @Prop() public data: any;

        // 是否完成任务，默认为否
        @Prop() public readonly isTaskDone?: any;
        /**
         * 计算属性(当前值)
         * @type {any}
         * @memberof DropDownList
         */
        set curIsTaskDone(val: any) {
            const type: string = this.$util.typeOf(val);
            val = Object.is(type, 'null') || Object.is(type, 'undefined') ? undefined : val;

        }
        /**
         * 获取值对象
         *
         * @memberof DropDownList
         */
        get curIsTaskDone() {
            return this.isTaskDone;
        }


        /**
         * 任务名称
         */
        @Prop() public readonly taskName?:string;

        /**
         * 计算属性(当前值)
         * @type {any}
         * @memberof DropDownList
         */
        set curTaskName(val: any) {
            const type: string = this.$util.typeOf(val);
            val = Object.is(type, 'null') || Object.is(type, 'undefined') ? undefined : val;
            this.$emit('changeName', val);
        }

        /**
         * 获取值对象
         *
         * @memberof DropDownList
         */
        get curTaskName() {
            return this.taskName;
        }

        /**
         * 是否正在编辑任务名称，默认false
         */
        public isEditTaskName: boolean = false;

        /**
         * 实体服务对象
         *
         * @type {TaskService}
         * @memberof TaskEditViewBase
         */
        public appEntityService: TaskService = new TaskService;

        /**
         * 避免回车键换行
         */
        public keydownTaskName(e: any) {
            if (e.keyCode === 13) {
                // 避免回车键换行
                e.preventDefault();

            }
        }

        /**
         * 更新任务名称
         */
        public keyupTaskName(e: any) {
            if (e.keyCode === 13) {
                this.isEditTaskName = false;
                // console.log('更新任务名称');
                if (this.taskName) {
                    this.updateTaskById({name: this.taskName});
                }
            }
        }

        /**
         * 失去焦点之后,更新任务名称
         */
        public taskNameTextLoseFocus() {
            this.isEditTaskName = false;
            if (this.taskName) {
                this.updateTaskById({name: this.taskName});
            }
            this.$forceUpdate();
        }

        /**
         * 更新任务
         */
        public async updateTaskById(json: any) {
            return new Promise((resolve: any, reject: any) => {
                let searchTaskByTaskId: Promise<any> = this.appEntityService.searchTaskByTaskId('tasks/' + this.data.id, {}, true);
                searchTaskByTaskId.then((response) => {
                    if (response && response.status === 200) {
                        if (response.data) {
                            let context: any = {task: this.data.id};
                            let data = response.data;
                            Object.assign(data, json);
                            let result: Promise<any> = this.appEntityService.Update(context, data, true);
                            result.then((response) => {
                                if (response.status === 200) {
                                    // todo getActionData
                                    this.$emit('getActionData', this.data.id);
                                    this.$emit('reload', {});
                                }
                            }).catch(response => {
                                // console.log(fetch);
                                this.$Notice.error({title: '错误', desc: response.data.detail});
                                reject(response);
                            });
                        }
                    }
                }).catch(response => {
                    // console.log(fetch);
                    this.$Notice.error({title: '错误', desc: response.data.detail});
                    reject(response);
                });
            });
        }

        /**
         * 点击完成任务（当任务未完成时）,点击激活任务（当任务已完成时）
         */
        public completeTask() {
            // 重新开始,激活任务
            if (this.isTaskDone) {
                let context: any = {task: this.data.id};
                // ACTION_PARAMS_ACTIVATE.put("assignedTo", null);
                // ACTION_PARAMS_ACTIVATE.put("left", null);
                // ACTION_PARAMS_ACTIVATE.put("comment", "");
                let params: any = {id: this.data.id, left: 5, assignedto: this.data.assignedto, comment: ''};
                let data = {};
                Object.assign(data, params);
                let isloading = true;
                return new Promise((resolve: any, reject: any) => {
                    let result: Promise<any>;
                    result = this.appEntityService.Activate(context, data, isloading);
                    result.then((response) => {
                        console.log(response);
                        if (response.data) {
                            // this.task.status = 'doing';
                            // todo getActionData
                            this.$emit('getActionData', this.data.id);
                            this.$emit('reload', {});
                        } else {
                        }
                    }).catch(response => {
                        this.$Notice.error({title: '错误', desc: response.data.detail});
                        reject(response);
                    });
                });
            }
            // 完成任务
            else {
                let context: any = {task: this.data.id};
                /*ACTION_PARAMS_FINISH.put("currentConsumed", null) ;本次消耗 Double
                ACTION_PARAMS_FINISH.put("consumed", null); 总计消耗    Double
                ACTION_PARAMS_FINISH.put("assignedTo", null);   指派给 string
                ACTION_PARAMS_FINISH.put("finishedDate", null);   实际完成 yyyy-MM-dd
                ACTION_PARAMS_FINISH.put("comment", ""); 备注 string*/
                let params: any = {
                    currentconsumed: 5,
                    consumed: 2,
                    assignedto: this.data.assignedto,
                    finisheddate: this.getNowFormatDate2(),
                    comment: '',
                    id: this.data.id,
                    totaltime: 7,
                    multiple: "0"
                };
                let data = {};
                Object.assign(data, params);
                let isloading = true;
                return new Promise((resolve: any, reject: any) => {
                    let result: Promise<any>;
                    result = this.appEntityService.Finish(context, data, isloading);
                    result.then((response) => {
                        console.log(response);
                        if (response.data) {
                            // this.task.status = 'done';
                            // todo getActionData
                            this.$emit('getActionData', this.data.id);
                            this.$emit('reload', {});
                        } else {

                        }
                    }).catch(response => {
                        this.$Notice.error({title: '错误', desc: response.data.detail});
                        reject(response);
                    });
                });
            }
        }



        public getNowFormatDate2() {
            let date = new Date();
            let seperator1 = "-";
            let seperator2 = ":";
            let month: any = date.getMonth() + 1;
            let strDate: any = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            return date.getFullYear() + seperator1 + month + seperator1 + strDate;
        }



    }
</script>

<style lang='less'>
    @import './app-taskname.less';
</style>